<?php

class DiaryAttachmentModel
{
    private $diaryAttachmentKeyPrefix   =   'DA/';

    public function addDiaryAttachment($diaryInfo)/*{{{*/
    {
        if (empty($diaryInfo['uid']) || empty($diaryInfo['bodyId']))
        {
            AC::$errorNo    =   'DAM001';
            return  FALSE;
        }

        $data['uid']        =   $diaryInfo['uid'];
        $data['bodyId']     =   $diaryInfo['bodyId'];
        $data['uploadTime'] =   AC::SERVER_TIME;
        // 兼容评论附件,type1=日记 2=评论 3=私信
        $data['type']       =   $diaryInfo['type'];
        $data['type_id']    =   $diaryInfo['type_id'];
        // 附件类型 1=图片 2=语音
        $data['attachmentType'] = $diaryInfo['attachment_type'];
        $key    =   $this->diaryAttachmentKeyPrefix. $diaryInfo['uid'];
        
        $diaryInfo['attachment'] = array_slice($diaryInfo['attachment'],0,AC::$topicDiaryAttachmentLimit );
        foreach ($diaryInfo['attachment']   as  $var)
        {
            if(is_array($var)){
                $check = UK::check_upyun_node(AC::$hostUserBaseInfo['uid'], AC::$hostUserBaseInfo['account'], $var['path']) || UK::check_bqyun($var['path']);
                $data['attachmentPath']  =   $var['path'];
                $data['info'] =   $var['info'];
            }
            else{
                $check = UK::check_upyun_node(AC::$hostUserBaseInfo['uid'], AC::$hostUserBaseInfo['account'], $var) || UK::check_bqyun($var);
                $data['attachmentPath'] =   $var;
            }
            if(isset($diaryInfo['rpc']) && $diaryInfo['rpc'] == 1){
                $check = 1;
            }
            if (empty($var) || empty($check))   continue;
            Storage::addData($key, $data);
        }
        $data    =    array();
        foreach ($diaryInfo['voice']   as  $var)
        {
            if (empty($var))   continue;
            if(is_array($var)){
                $data['attachmentPath']  =   $var['path'];
                $data['info'] =   $var['info'];
            }
            else{
                 $data['attachmentPath'] =   $var;
            }
            Storage::addData($key, $data);
        }
        return  TRUE;
    }/*}}}*/

    public function saveAttachment($uid, $data)
    {
        if (empty($uid) || empty($data))
        {
            return false;
        }

        $key    =   $this->diaryAttachmentKeyPrefix. $uid;
        return Storage::addData($key, $data);
    }

    public function getDiaryAttachment($diaryInfo)/*{{{*/
    {
        if (empty($diaryInfo['uid']) || empty($diaryInfo['bodyId']))
        {
            AC::$errorNo    =   'DAM002';
            return  FALSE;
        }

        $key    =   $this->diaryAttachmentKeyPrefix. $diaryInfo['uid'];
        $where  =   array('bodyId' => $diaryInfo['bodyId'], 'status' => 0);
        $result =   Storage::getConditionManyData($key, $where);
        return  $result;
    }/*}}}*/

    public function getDiaryAttachmentList($diaryInfo)/*{{{*/
    {
    }/*}}}*/

    public function setDiaryAttachment($diaryInfo)/*{{{*/
    {
        if (empty($diaryInfo['uid']) || empty($diaryInfo['bodyId']))
        {
            AC::$errorNo    =   'DAM003';
            return  FALSE;
        }

        $data['uploadTime'] =   AC::SERVER_TIME;
        $data['status']     =   1;

        # No Attachment ! delete all!   /*{{{*/
        $key    =   $this->diaryAttachmentKeyPrefix. $diaryInfo['uid'];
        if (empty($diaryInfo['attachment'][0]))
        {
            $where  =   array('bodyId' => $diaryInfo['bodyId']);
            $result =   Storage::setConditionData($key, $data, $where);
            if (empty($result)) AC::$errorNo    =   'DAM004';

            return  TRUE;
        }/*}}}*/

        $oldAttachement =   $this->getDiaryAttachment($diaryInfo);
        # old attachment is null, so ,all insert    /*{{{*/
        if (empty($oldAttachement))
        {
            return  $this->addDiaryAttachment($diaryInfo);
        }/*}}}*/

        $transArray =   array_flip($diaryInfo['attachment']);
        $tmpArray   =   array();
        foreach ($oldAttachement    as  $attachmentInfo)
        {
            if (isset($transArray[$attachmentInfo['attachmentPath']]))
            {
                $tmpArray[] =   $attachmentInfo['attachmentPath'];
                unset($transArray[$attachmentInfo['attachmentPath']]);
            }
        }

        $oldAttachementNum  =   count($oldAttachement);
        $tmpArrayNum        =   count($tmpArray);
        $newAttachementNum  =   count($diaryInfo['attachment']);
        # no find repeat! /*{{{*/
        if (empty($tmpArrayNum))
        {
            # delete all
            $where  =   array('bodyId' => $diaryInfo['bodyId']);
            $result =   Storage::setConditionData($key, $data, $where);

            # add new
            return  $this->addDiaryAttachment($diaryInfo);
        }/*}}}*/

        # No new attachment, and no delete attachment   /*{{{*/
        if (($tmpArrayNum   ==  $oldAttachementNum) && ($tmpArrayNum == $newAttachementNum))
        {
            return  TRUE;
        }/*}}}*/

        # delete part attachment/*{{{*/
        if ($tmpArrayNum    !=  $oldAttachementNum)
        {
            $pathString =   "('". implode("', '", $diaryInfo['attachment']). "')";
            $where      =   ' bodyId = "'. $diaryInfo['bodyId']. '" AND attachmentPath NOT IN '. $pathString;
            $result     =   Storage::setConditionData($key, $data, $where);
        }/*}}}*/

        # add part attachment/*{{{*/
        if (count($transArray)  >   0)
        {
            $newAttachment  =   array_keys($transArray);
            $diaryInfo['attachment']    =   $newAttachment;
            return  $this->addDiaryAttachment($diaryInfo);
        }/*}}}*/

        return  TRUE;
    }/*}}}*/

    public function removeDiaryAttachment($diaryInfo)/*{{{*/
    {
        if (empty($diaryInfo['uid']) || empty($diaryInfo['bodyId']))
        {
            AC::$errorNo    =   'DAM005';
            return  FALSE;
        }

        $data['uploadTime'] =   AC::SERVER_TIME;
        $data['status']     =   1;

        $key    =   $this->diaryAttachmentKeyPrefix. $diaryInfo['uid'];
        // 删除日记时只将日记本身的附件删除
        $where  =   array('bodyId' => $diaryInfo['bodyId'],'type'=>1);
        $result =   Storage::setConditionData($key, $data, $where);
        if (empty($result)){
        	AC::$errorNo    =   'DAM006';
        	return false;
		}

        return  TRUE;
    }/*}}}*/
    /**
     * 获取附件,并根据类型分类
     * 1=图片 2=语音
     * @param unknown $diaryInfo
     * @return boolean|Ambigous <unknown, boolean, multitype:>
     */
    public function getDiaryAllAttachment($diaryInfo)/*{{{*/
    {
        if (empty($diaryInfo['uid']) || empty($diaryInfo['bodyId']))
        {
            AC::$errorNo    =   'DAM002';
            return  FALSE;
        }
    
        $key    =   $this->diaryAttachmentKeyPrefix. $diaryInfo['uid'];
        $where  =   ' bodyId =  '.$diaryInfo['bodyId'].' AND status = 0 AND type in (0,1) ';
        $result =   Storage::getConditionManyData($key, $where);
        $list   =   array('voiceList'=>array(),'attachmentList'=> array(), 'videoList'=>array(), 'linkList'=>array());
        if (empty($result))return $list;
        foreach ($result as $value){
            switch (intval($value['attachmentType'])){
                case 2:$list['voiceList'][]    =    $value;break;
                case 3:$list['videoList'][]    =    $value;break;
		case 4:$list['linkList'][]     =    $value;break;
                default:$list['attachmentList'][]   =    $value;
            }
        }

        return  $list;
    }/*}}}*/
 
    /**
     * 获取私信的附件
     * @param unknown $commentInfo
     * @return boolean|Ambigous <multitype:multitype: , unknown, boolean, multitype:>
     */
    public function getMessageAttachment($commentInfo){
        if (empty($commentInfo['last_attachment'])){
            AC::$errorNo    =   'DAM002';
            return  FALSE;
        }
        $key    =   $this->diaryAttachmentKeyPrefix. $commentInfo['uid'];
        $where  =   array('type_id' => $commentInfo['last_attachment'], 'type'=>3,'status' => 0);
        $result =   Storage::getConditionManyData($key, $where);
        $list   =   array('voiceList'=>array(),'attachmentList'=> array());
        if (!empty($result)){
            foreach ($result as $value){
                if (stripos($value['attachmentPath'], 'http://')===0){//将表情云的地址替换掉
                    $url_parse = parse_url($value['attachmentPath']);
                    $url_parse['host'] && $value['attachmentPath'] = str_ireplace('http://'.$url_parse['host'],  AC::getProtocolUriByOS(AC::$cdn_url_biaoqingyun), $value['attachmentPath']  );
                }
                if (intval($value['attachmentType']) == 2){
                    $list['voiceList'][]    =    $value;
                    continue;
                }
                $list['attachment'][]    =    $value;
            }
        }
    
        return  $list;
    }
    
    /**
     * 获取群聊附件
     * @param unknown $commentInfo
     * @return boolean|Ambigous <multitype:multitype: , unknown, boolean, multitype:>
     */
    public function getChatGroupAttachment($commentInfo){
        if (empty($commentInfo['last_attachment'])){
            AC::$errorNo    =   'DAM002';
            return  FALSE;
        }
        $key    =   $this->diaryAttachmentKeyPrefix. $commentInfo['uid'];
        $where  =   array('type_id' => $commentInfo['last_attachment'], 'type'=>4,'status' => 0);
        $result =   Storage::getConditionManyData($key, $where);
        $list   =   array('voiceList'=>array(),'attachmentList'=> array());
        if (!empty($result)){
            foreach ($result as $value){
                if (stripos($value['attachmentPath'], 'http://')===0){//将表情云的地址替换掉
                    $url_parse = parse_url($value['attachmentPath']);
                    $url_parse['host'] && $value['attachmentPath'] = str_ireplace('http://'.$url_parse['host'],  AC::getProtocolUriByOS(AC::$cdn_url_biaoqingyun), $value['attachmentPath']  );
                }
                if (intval($value['attachmentType']) == 2){
                    $list['voiceList'][]    =    $value;
                    continue;
                }
                $list['attachment'][]    =    $value;
            }
        }
    
        return  $list;
    }
    
    /**
     * 删除附件
     * @param unknown $info
     * @return boolean
     */
    public function removeMessageAttachment($diaryInfo){
        if (empty($diaryInfo['uid']) || empty($diaryInfo['id']))
        {
            AC::$errorNo    =   'DAM005';
            return  FALSE;
        }
        
        $data['uploadTime'] =   AC::SERVER_TIME;
        $data['status']     =   1;
        
        $key    =   $this->diaryAttachmentKeyPrefix. $diaryInfo['uid'];
        $where  =   array('type_id' => $diaryInfo['id'],'type'=>3);
        $result =   Storage::setConditionData($key, $data, $where);
        if (empty($result)) AC::$errorNo    =   'DAM006';
        
        return  TRUE;
    }
    
    public function  getDiaryImageAttachmentByUid($uid,$start,$length)/*{{{*/
    {
    	$key    =   $this->diaryAttachmentKeyPrefix.$uid;
    	$where  =   ' attachmentType = 1 AND type in (0,1) AND status = 0';	
    	$orderBy=   ' id DESC ';
    	
    	$result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
    	return  $result;
    
    }
    
    public function  getDiaryImageAttachmentByUidCount($uid)/*{{{*/
    {
    	$key    =   $this->diaryAttachmentKeyPrefix.$uid;
    	$where  =   ' attachmentType = 1 AND type in (0,1) AND status = 0';
    	$result =   Storage::countDataRow($key, $where);
    	return  $result;
    }

    /**
     * 软删除附件
     * @param $uid
     * @param $articleBodyId
     * @param $type
     * @return bool
     */
    public function delAttachment($uid, $articleBodyId, $type){
        if (empty($uid) || empty($articleBodyId))
        {
            AC::$errorNo    =   'DAM005';
            return  FALSE;
        }
        $data['uploadTime'] =   AC::SERVER_TIME;
        $data['status']     =   1;
        $key    =   $this->diaryAttachmentKeyPrefix. $uid;
        $where  =   array('type_id' => $articleBodyId,'type'=> $type);
        $result =   Storage::setConditionData($key, $data, $where);
        if (empty($result)) AC::$errorNo    =   'DAM006';
        return  TRUE;
    }

    /**
     * 获取评论附件
     * @param $uid
     * @param $bodyId
     * @param $type
     * @param $typeId
     * @return array|bool
     */
    public function getCommentAttachment($uid, $bodyId, $type, $typeId){
        if(empty($uid) || empty($bodyId) || empty($type) || empty($typeId)){
            return false;
        }
        $key    =   $this->diaryAttachmentKeyPrefix. $uid;
        $where  =   ' bodyId =  ' . $bodyId . ' AND status = 0 AND type = ' . $type . ' AND type_id = ' . $typeId;
        $result =   Storage::getConditionManyData($key, $where);
        return $result;
    }

    /**
     * 获取附件
     * @param $uid
     * @param $type
     * @param $typeId
     * @return array|bool
     */
    public function getAttachment($uid, $type, $typeId){
        if(empty($uid) || empty($type) || empty($typeId)){
            return false;
        }
        $key    =   $this->diaryAttachmentKeyPrefix. $uid;
        $where  =   ' status = 0 AND type = ' . $type . ' AND type_id = ' . $typeId;
        $result =   Storage::getConditionManyData($key, $where);
        return $result;
    }

}
